package coc.example.script.crawler;

import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import coc.core.Crawler;
import coc.core.CrawlerConfig;
import coc.core.CrawlerResult;
import coo.base.exception.UncheckedException;

public abstract class BaseCrawlerExecutor extends ThreadPoolExecutor {
	protected abstract Crawler genCrawler(CrawlerConfig crawlerConfig);

	public BaseCrawlerExecutor() {
		super(1, Integer.MAX_VALUE, 0, TimeUnit.SECONDS,
				new LinkedBlockingQueue<Runnable>());
	}

	public CrawlerResult execute(CrawlerConfig crawlerConfig) {
		try {
			Crawler crawler = genCrawler(crawlerConfig);
			Future<CrawlerResult> future = submit(crawler);
			return future.get();
		} catch (Exception e) {
			throw new UncheckedException("执行爬虫时发生异常。", e);
		}
	}
}
